<template>
  <ElDialog
    v-model="dialogVisible"
    title="商品分类管理"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="category-dialog-content">
      <!-- 工具栏 -->
      <div class="toolbar">
        <ElButton type="primary" @click="showAddDialog">
          <ElIcon><Plus /></ElIcon>
          新增分类
        </ElButton>
        <ElButton @click="refreshData">
          <ElIcon><Refresh /></ElIcon>
          刷新
        </ElButton>
      </div>

      <!-- 分类树 -->
      <ElTree
        ref="treeRef"
        :data="categoryTreeData"
        :props="{ label: 'categoryName', children: 'children' }"
        node-key="id"
        :expand-on-click-node="false"
        :default-expand-all="true"
        class="category-tree"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <span class="node-label">{{ data.categoryName }}</span>
            <div class="node-actions">
              <ElButton
                type="primary"
                text
                size="small"
                @click="handleEdit(data)"
              >
                编辑
              </ElButton>
              <ElButton
                type="success"
                text
                size="small"
                @click="handleAddChild(data)"
              >
                添加子分类
              </ElButton>
              <ElButton
                type="danger"
                text
                size="small"
                @click="handleDelete(data)"
              >
                删除
              </ElButton>
            </div>
          </div>
        </template>
      </ElTree>
    </div>

    <template #footer>
      <ElButton @click="handleClose">关闭</ElButton>
    </template>

    <!-- 分类编辑弹窗 -->
    <ElDialog
      v-model="editDialogVisible"
      :title="editType === 'add' ? '新增分类' : '编辑分类'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
      append-to-body
    >
      <ElForm
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <ElFormItem
          label="上级分类"
          prop="parentId"
          v-if="editType === 'add' && parentCategory"
        >
          <ElInput :value="parentCategory.categoryName" disabled />
        </ElFormItem>

        <ElFormItem label="分类名称" prop="categoryName">
          <ElInput
            v-model="formData.categoryName"
            placeholder="请输入分类名称"
          />
        </ElFormItem>

        <ElFormItem label="分类编码" prop="categoryCode">
          <ElInput
            v-model="formData.categoryCode"
            placeholder="请输入分类编码"
          />
        </ElFormItem>

        <ElFormItem label="排序" prop="orderNum">
          <ElInputNumber
            v-model="formData.orderNum"
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </ElFormItem>

        <ElFormItem label="状态" prop="status">
          <ElRadioGroup v-model="formData.status">
            <ElRadio :label="1">启用</ElRadio>
            <ElRadio :label="0">禁用</ElRadio>
          </ElRadioGroup>
        </ElFormItem>

        <ElFormItem label="备注" prop="remark">
          <ElInput
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <ElSpace>
          <ElButton @click="editDialogVisible = false">取消</ElButton>
          <ElButton
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            确定
          </ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useWmsStore } from "@/store/modules/wms";
import { WmsItemCategoryService } from "@/api/wms/basicApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsItemCategoryDialog" });

// Props
interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
});

// Emits
interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "submit"): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const wmsStore = useWmsStore();

// 弹窗状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// 分类树数据
const categoryTreeData = computed(() => {
  return wmsStore.itemCategoryTreeList || [];
});

// 编辑弹窗
const editDialogVisible = ref(false);
const editType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const parentCategory = ref<WMS.Basic.ItemCategoryInfo | null>(null);

// 表单数据
const formData = ref<Partial<WMS.Basic.ItemCategoryInfo>>({
  categoryName: "",
  categoryCode: "",
  parentId: undefined,
  orderNum: 0,
  status: 1,
  remark: "",
});

// 表单验证规则
const formRules: FormRules = {
  categoryName: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 50, message: "分类名称长度在2-50个字符", trigger: "blur" },
  ],
  categoryCode: [
    { required: true, message: "请输入分类编码", trigger: "blur" },
    { min: 2, max: 50, message: "分类编码长度在2-50个字符", trigger: "blur" },
  ],
  orderNum: [{ required: true, message: "请输入排序", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听弹窗显示
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      refreshData();
    }
  },
);

// 刷新数据
const refreshData = () => {
  wmsStore.getItemCategoryTreeList();
};

// 显示新增弹窗
const showAddDialog = () => {
  editType.value = "add";
  parentCategory.value = null;
  formData.value = {
    categoryName: "",
    categoryCode: "",
    parentId: undefined,
    orderNum: 0,
    status: 1,
    remark: "",
  };
  editDialogVisible.value = true;
};

// 编辑分类
const handleEdit = (data: WMS.Basic.ItemCategoryInfo) => {
  editType.value = "edit";
  parentCategory.value = null;
  formData.value = { ...data };
  editDialogVisible.value = true;
};

// 添加子分类
const handleAddChild = (data: WMS.Basic.ItemCategoryInfo) => {
  editType.value = "add";
  parentCategory.value = data;
  formData.value = {
    categoryName: "",
    categoryCode: "",
    parentId: data.id,
    orderNum: 0,
    status: 1,
    remark: "",
  };
  editDialogVisible.value = true;
};

// 删除分类
const handleDelete = async (data: WMS.Basic.ItemCategoryInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${data.categoryName}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await WmsItemCategoryService.deleteItemCategory(data.id);
    ElMessage.success("删除成功");
    refreshData();
    emit("submit");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    submitLoading.value = true;

    if (editType.value === "add") {
      await WmsItemCategoryService.createItemCategory(
        formData.value as WMS.Basic.ItemCategoryCreateParams,
      );
      ElMessage.success("新增分类成功");
    } else {
      await WmsItemCategoryService.updateItemCategory(
        formData.value.id!,
        formData.value,
      );
      ElMessage.success("更新分类成功");
    }

    editDialogVisible.value = false;
    refreshData();
    emit("submit");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.category-dialog-content {
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }

  .category-tree {
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    padding: 8px;
    max-height: 400px;
    overflow-y: auto;

    .tree-node {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      padding-right: 8px;

      .node-label {
        flex: 1;
        font-weight: 500;
      }

      .node-actions {
        display: flex;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.2s;
      }

      &:hover .node-actions {
        opacity: 1;
      }
    }
  }
}
</style>
